Dynamic Stack
Dynamic stack is FIFO data structure in which any number of data can be inserted. It is implemented using Linked List, in which only one end is defined to insert (push) or remove (pop) elements named top.
import java.util.*; class dynamicStack{ public static void main(String args[]){ node temp, top=null; System.out.print("Creating Dynamic Stack!!!"); int choice; String str; Scanner sc = new Scanner(System.in); while(true){ System.out.print("\n1.Push\n2.Pop\n3.Show\nChoice:"); choice = sc.nextInt(); switch(choice){ case 1: System.out.println("Enter Data:"); str = sc.nextLine(); str = sc.nextLine(); temp = new node(); temp.data = str; temp.address = null; if(top == null){ top = temp; }else{ temp.address = top; top = temp; } break; case 2: System.out.println("Popping Stack!!!"); System.out.println("Top of Stack : "+top.data); temp = top.address; top = temp; temp = null; break; case 3: System.out.println("Show contents of Stack: \n"); if(top != null){ for(temp=top;temp.address!=null;temp=temp.address){ System.out.print(temp.data+" "); } System.out.print(temp.data+" "); } break; default: System.exit(0); break; } } } } Output: Creating Dynamic Stack!!! 1.Push 2.Pop 3.Show Choice:1 Enter Data: apple 1.Push 2.Pop 3.Show Choice:1 Enter Data: mango 1.Push 2.Pop 3.Show Choice:3 Show contents of Stack: mango apple 1.Push 2.Pop 3.Show Choice:2 Popping Stack!!! Top of Stack : mango 1.Push 2.Pop 3.Show Choice: